#include "headers/MarkedGameManager.h"
#include <QDebug>
#include <QDir>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>

MarkedGameManager::MarkedGameManager(QObject *parent)
    : QObject(parent)
{
    // 设置JSON文件路径
    m_jsonFilePath = QDir::currentPath() + "/marked_games.json";
    qDebug() << "Marked games JSON path:" << m_jsonFilePath;

    // 若文件不存在
    QFile file(m_jsonFilePath);
    if (!file.exists()) {
        if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
            QJsonObject rootObj;
            rootObj["marked_games"] = QJsonArray(); // 初始化空数组，保证格式正确
            QJsonDocument doc(rootObj);
            file.write(doc.toJson(QJsonDocument::Indented)); // 格式化写入，便于人工编辑
            file.close();
            qDebug() << "Created empty marked games JSON file.";
        }
    }
}

// 读取JSON中的标记进程列表
QStringList MarkedGameManager::loadMarkedGames()
{
    QFile file(m_jsonFilePath);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "Failed to open marked games file for reading:" << m_jsonFilePath;
        return QStringList();
    }

    QByteArray data = file.readAll();
    QJsonDocument doc = QJsonDocument::fromJson(data);
    if (!doc.isObject()) {
        qDebug() << "JSON file format error: not an object.";
        file.close();
        return QStringList();
    }

    QJsonObject root = doc.object();
    QJsonArray gamesArray = root["marked_games"].toArray();

    QStringList markedGames;
    for (const auto &item : gamesArray) {
        markedGames << item.toString();
    }

    file.close();
    return markedGames;
}

// 添加新标记的进程
bool MarkedGameManager::addMarkedGame(const QString &processName)
{
    // 先读取已有列表
    QStringList existingGames = loadMarkedGames();
    if (existingGames.contains(processName, Qt::CaseInsensitive)) {
        qDebug() << "Process already marked (case-insensitive):" << processName;
        return false;
    }

    // 添加新进程
    existingGames << processName;

    // 写入JSON文件
    QFile file(m_jsonFilePath);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        qDebug() << "Failed to open marked games file for writing:" << m_jsonFilePath;
        return false;
    }

    QJsonObject root;
    QJsonArray gamesArray;
    for (const QString &name : existingGames) {
        gamesArray.append(name);
    }
    root["marked_games"] = gamesArray;

    QJsonDocument doc(root);
    file.write(doc.toJson(QJsonDocument::Indented));
    file.close();

    return true;
}

// 删除指定标记进程
bool MarkedGameManager::removeMarkedGame(const QString &processName)
{
    QStringList existingGames = loadMarkedGames();
    if (existingGames.isEmpty()) {
        qDebug() << "No marked games to remove.";
        return false;
    }

    bool removed = false;
    for (int i = 0; i < existingGames.size(); ++i) {
        if (existingGames[i].compare(processName, Qt::CaseInsensitive) == 0) {
            existingGames.removeAt(i);
            removed = true;
            break;
        }
    }

    if (!removed) {
        qDebug() << "Process not found in marked list:" << processName;
        return false;
    }

    QFile file(m_jsonFilePath);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) {
        qDebug() << "Failed to open marked games file for writing (remove):" << m_jsonFilePath;
        return false;
    }

    QJsonObject root;
    QJsonArray gamesArray;
    for (const QString &name : existingGames) {
        gamesArray.append(name);
    }
    root["marked_games"] = gamesArray;

    QJsonDocument doc(root);
    file.write(doc.toJson(QJsonDocument::Indented));
    file.close();

    qDebug() << "Removed marked process:" << processName;
    return true;
}

// 检查进程是否已标记，忽略大小写
bool MarkedGameManager::isProcessMarked(const QString &processName)
{
    return loadMarkedGames().contains(processName, Qt::CaseInsensitive);
}
